# views.py: 路由，视图函数
# 蓝图
from flask import Blueprint, render_template,request,g,session,current_app
from .models import *
from .exts import cache
import time
blue = Blueprint('user',__name__)
# blue2 = Blueprint('product',__name__)

# 使用缓存
@blue.route('/')
@cache.cached(timeout=40)  # 给视图函数加一个缓存20s
def index1():
    print('index1')
    print('index视图函数中',g.star)
    time.sleep(5)
    return '<h1>index123444</h1>'

# AOP ：切面编程
# 钩子：钩子函数
#   也叫做中间件
# before_request() 每一次请求之前访问
@blue.before_request
def before():
    print('before_request')

    # request
    # print(request.path)
    # print(request.method)
    # print(request.remote_addr)  # 客户端ip

    # 简单的反爬
    print(request.user_agent)  # python-requests/2.32.4
    # if 'python' in request.user_agent.string:
    #     return '正在使用Python爬虫'

    # 针对IP做反爬
    ip = request.remote_addr
    # cache.get()
    # cache.set()
    if cache.get(ip):
        return '被发现了'
    else:
        # 对每个IP设置一个缓存，1秒内不让重复访问
        cache.set(ip,'value',timeout=1)


    # flask 内置对象
    # request:请求对象
    # session：会话对象
    # g:global 全局对象
    # current_app:flask应用对象
    g.star = '张'
    print(g.star)
    print(current_app)  # <Flask 'App'>
    print(current_app.config)  # <Config {'DEBUG': True, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'SECRET_KEY': None, 'SECRET_KEY_FALLBACKS': None,

@blue.route('/template/')
def template():
    return render_template('template.html')